package com.tulele.vtool.aop;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Aspect
@Component
public class WebLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

    @Autowired
    private HttpServletRequest request;

    /**
     * 环绕触发
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.tulele.vtool.handler..*.*(..))")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {

        // 获取输入参数
        Map<String, Object> inputParamMap = Maps.newHashMapWithExpectedSize(2);
        Object [] argsAry = pjp.getArgs();
        if (argsAry.length == 1) {
            inputParamMap.put("reqParam", pjp.getArgs()[0]);
        } else if (argsAry.length == 2) {
            inputParamMap.put("reqHeaderParam", pjp.getArgs()[0]);
            inputParamMap.put("reqParam", pjp.getArgs()[1]);
        }


        // 获取请求地址
        String requestPath = request.getRequestURI();

        // 执行完方法的返回值：调用proceed()方法，就会触发切入点方法执行
        Map<String, Object> outputParamMap = Maps.newHashMapWithExpectedSize(1);

        //执行目标方法之前
        if (!requestPath.contains("wechat")) {
            logger.info("[BeforeReqUrl] = " + requestPath + " [reqParam] = " + JSONObject.toJSONString(inputParamMap));
        }
        // result的值就是被拦截方法的返回值
        Object result = pjp.proceed();

        //执行目标方法之后
        outputParamMap.put("respResult", result);

        if (!requestPath.contains("wechat")) {
            logger.info("[AfterReqUrl] = " + requestPath + " [reqParam] = " + JSONObject.toJSONString(inputParamMap) + " [respResult] = " + JSONObject.toJSONString(outputParamMap));
        }


        return result;
    }

}
